/*
 * Created by Jaren at 2022/5/5 16:46
 */
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';

import 'package:inmotion_protocol/util/byte_util.dart';

class LorinLightEffectFileGenerator {
  static const sizePeerColor = 3;

  static Uint8ClampedList generate(
      int lightCountPeerFrame,
      int id,
      int format,
      int frameCount,
      int interval,
      int relatedToSpeed,
      List<int> colors) {
    interval = interval ~/ 10;
    int frameSize = frameCount * lightCountPeerFrame * sizePeerColor;
    int totalLength = 1 + 3 + 4 + 4 + 4 + 2 + 2 + frameSize;
    Uint8ClampedList bytes = Uint8ClampedList(totalLength);
    int offset = 0;
    bytes[offset] = format;
    offset++;
    // 保留3byte
    offset += 3;
    ByteUtil.num2BytesLe(id, 4, bytes, offset);
    offset += 4;
    ByteUtil.num2BytesLe(frameCount, 4, bytes, offset);
    offset += 4;
    ByteUtil.num2BytesLe(frameSize, 4, bytes, offset);
    offset += 4;
    ByteUtil.num2BytesLe(interval, 2, bytes, offset);
    offset += 2;
    ByteUtil.num2BytesLe(relatedToSpeed, 2, bytes, offset);
    offset += 2;

    // 填充colors
    for (int i = 0; i < colors.length; i++) {
      ByteUtil.num2Bytes(correctColor(colors[i]), sizePeerColor, bytes, offset);
      offset += sizePeerColor;
    }

    return bytes;
  }

  static int correctColor(int color) {
    return Color.fromARGB(
            0,
            _correctColorR(Color(color).red),
            _correctColorG(Color(color).green),
            _correctColorB(Color(color).blue))
        .value;
  }

  // 校正颜色
  static int _correctColorR(int r) {
    return (pow(r, 3) / 255) ~/ 255;
  }

  static int _correctColorG(int g) {
    return (pow(g, 3) / 255) ~/ 255;
  }

  static int _correctColorB(int b) {
    return (pow(b, 3) / 255) ~/ 255;
  }
}
